import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/content.dart';
import '../providers/audio_provider.dart';
import '../config/app_theme.dart';

/// 高亮文本组件（类似歌词滚动）
class HighlightText extends StatefulWidget {
  final List<Sentence> sentences;
  final ScrollController? parentScrollController; // 接收父级滚动控制器

  const HighlightText({
    super.key, 
    required this.sentences,
    this.parentScrollController,
  });

  @override
  State<HighlightText> createState() => _HighlightTextState();
}

class _HighlightTextState extends State<HighlightText> {
  final Map<int, GlobalKey> _sentenceKeys = {};
  
  // 用户手动滑动控制
  bool _isUserScrolling = false;
  Timer? _scrollResumeTimer;
  
  // 用于防抖的定时器 - 防止自动滚动过于频繁
  Timer? _autoScrollDebounceTimer;
  int? _pendingScrollIndex;
  int? _lastScrolledIndex; // 记录上次滚动的索引

  @override
  void initState() {
    super.initState();
    // 为每个句子创建 key
    for (int i = 0; i < widget.sentences.length; i++) {
      _sentenceKeys[i] = GlobalKey();
    }
  }

  @override
  void dispose() {
    _scrollResumeTimer?.cancel();
    _autoScrollDebounceTimer?.cancel();
    super.dispose();
  }

  void _scrollToSentence(int index) {
    // 如果用户正在滑动，不执行自动滚动
    if (_isUserScrolling) {
      debugPrint('用户正在滑动，跳过自动滚动到句子 $index');
      return;
    }
    
    // 如果已经滚动到这个位置，不重复滚动
    if (_lastScrolledIndex == index) {
      return;
    }
    
    // 使用防抖，避免滚动过于频繁
    _pendingScrollIndex = index;
    _autoScrollDebounceTimer?.cancel();
    _autoScrollDebounceTimer = Timer(const Duration(milliseconds: 200), () {
      if (_pendingScrollIndex == index && !_isUserScrolling && mounted) {
        _performScroll(index);
      }
    });
  }
  
  void _performScroll(int index) {
    final key = _sentenceKeys[index];
    if (key != null && key.currentContext != null) {
      try {
        Scrollable.ensureVisible(
          key.currentContext!,
          duration: const Duration(milliseconds: 400),
          curve: Curves.easeInOut,
          alignment: 0.25, // 滚动到屏幕上方 1/4 位置
        );
        _lastScrolledIndex = index;
        debugPrint('自动滚动到句子 $index');
      } catch (e) {
        debugPrint('自动滚动失败: $e');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AudioProvider>(
      builder: (context, provider, child) {
        // 自动滚动到当前句子（仅在非用户滑动状态下）
        if (provider.currentSentenceIndex >= 0 && 
            provider.currentSentenceIndex < widget.sentences.length &&
            !_isUserScrolling) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _scrollToSentence(provider.currentSentenceIndex);
          });
        }

        return NotificationListener<ScrollNotification>(
          onNotification: (notification) {
            // 监听用户手动滑动（只监听直接的用户操作）
            if (notification is ScrollStartNotification && notification.dragDetails != null) {
              // 用户开始拖动，立即暂停自动滚动
              if (!_isUserScrolling) {
                setState(() {
                  _isUserScrolling = true;
                });
                debugPrint('用户开始滑动，暂停自动滚动');
                // 取消所有待执行的自动滚动
                _autoScrollDebounceTimer?.cancel();
              }
            } else if (notification is ScrollUpdateNotification && notification.dragDetails != null) {
              // 用户正在拖动，持续取消自动滚动
              _autoScrollDebounceTimer?.cancel();
              // 重置恢复定时器
              _scrollResumeTimer?.cancel();
            } else if (notification is ScrollEndNotification && notification.dragDetails != null) {
              // 用户停止滑动，延迟恢复自动滚动
              _scrollResumeTimer?.cancel();
              _scrollResumeTimer = Timer(const Duration(milliseconds: 1500), () {
                if (mounted) {
                  setState(() {
                    _isUserScrolling = false;
                  });
                  debugPrint('用户停止滑动 1.5秒，恢复自动滚动');
                  // 立即滚动到当前句子
                  if (provider.currentSentenceIndex >= 0) {
                    _lastScrolledIndex = null; // 重置，允许滚动
                    _scrollToSentence(provider.currentSentenceIndex);
                  }
                }
              });
            }
            return false;
          },
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: widget.sentences.asMap().entries.map((entry) {
                final index = entry.key;
                final sentence = entry.value;
                final isHighlight = provider.currentSentenceIndex == index;

                return GestureDetector(
                  key: _sentenceKeys[index],
                  onTap: () {
                    provider.jumpToSentence(index);
                  },
                  child: Container(
                    margin: const EdgeInsets.only(bottom: 4),
                    padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                    child: Text(
                      sentence.text,
                      style: TextStyle(
                        fontSize: isHighlight ? 18 : 16,
                        height: 1.8,
                        color: isHighlight ? AppTheme.textPrimary : AppTheme.textSecondary,
                        fontWeight: isHighlight ? FontWeight.w600 : FontWeight.normal,
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
        );
      },
    );
  }
}

